package com.colde.salary.shiro.realms;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import com.colde.salary.common.enumeration.ResponseCodeEnum;
import com.colde.salary.exception.ServiceException;
import com.colde.salary.model.User;
import com.colde.salary.service.IUserService;

public class UserRealm extends AuthorizingRealm{

	@Autowired
	private IUserService userService;
	
	@Override
	public void setName(String name) {
		// TODO Auto-generated method stub
		super.setName(name);
	}

	//用于认证
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		
		 //加这一步的目的是在Post请求的时候会先进认证，然后在到请求
        if (null == token.getPrincipal()) {
            return null;
        }

		// 1.从主体信息传过来的认证信息获取用户名username
		String username =  token.getPrincipal().toString();
		//String password = new String((char[])token.getCredentials()); 	//得到密码
		User user = User.builder().nickname(username).build();
		// 2.通过用户名从数据库获取凭证
		user = userService.selectOne(user);
		if(null == user) {
			return null;
		}
		String password = user.getPwd();
		SimpleAuthenticationInfo  authenticationInfo = new SimpleAuthenticationInfo(username, password, getName());
		return authenticationInfo;
	}
	
	//用于授权
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection pc) {
		return null;
	}
}
